//
//  GameScene.swift
//  SyntheticWatermelon
//
//  Created by wxc on 2021/1/28.
//

import GameplayKit
import SpriteKit

struct BitMaskType {
    var A = 1
    var B = 2
    var C = 3
    var D = 4
    var E = 5
    var F = 6
    
    var G = 7
    var H = 8
    var I = 9
    var J = 10
    var K = 11
}

class GameScene: SKScene, SKPhysicsContactDelegate {
    var entities = [GKEntity]()
    var graphs = [String: GKGraph]()

    private var lastUpdateTime: TimeInterval = 0
    private var label: SKSpriteNode?
    private var spinnyNode: SKShapeNode?

    private var currentInex : Int = 1
        
        
    override func sceneDidLoad() {
        lastUpdateTime = 0

        // Get label node from scene and store it for use later
        label = SKSpriteNode.init()
        label?.size = CGSize.init(width: 100, height: 100)
        label?.position = CGPoint.init(x: frame.midX, y: frame.midY + 300)
        
        self.addChild(label!)
        
//        if let label = self.label {
//            label.alpha = 0.0
//            label.run(SKAction.fadeIn(withDuration: 2.0))
//        }

        // Create shape node to use during mouse interaction
        let w = (size.width + size.height) * 0.05
        spinnyNode = SKShapeNode(rectOf: CGSize(width: w, height: w), cornerRadius: w * 0.3)

        if let spinnyNode = self.spinnyNode {
            spinnyNode.lineWidth = 2.5

            spinnyNode.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(Double.pi), duration: 1)))
            spinnyNode.run(SKAction.sequence([SKAction.wait(forDuration: 0.5),
                                              SKAction.fadeOut(withDuration: 0.5),
                                              SKAction.removeFromParent()]))
        }

        physicsWorld.contactDelegate = self
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let label = self.label {
            label.run(SKAction(named: "Pulse")!, withKey: "fadeInOut")
        }

        for touch in touches {
            
            let rand = currentInex
            
            let node = SKSpriteNode()
            node.position = touch.location(in: self)
            node.color = badayColor(i: Int(rand)-1)
            node.size = CGSize(width: 10 * Int(rand), height: 10 * Int(rand))
            node.physicsBody = SKPhysicsBody(rectangleOf: node.frame.size)
            node.name = "\(rand)"
            node.physicsBody?.categoryBitMask = UInt32(rand)
            node.physicsBody?.contactTestBitMask = UInt32(rand)
            node.texture = SKTexture.init(image: UIImage.init(named: "\(rand)")!)
//            node.physicsBody?.collisionBitMask = UInt32(rand)

            /* 1.一个标记，定义了这个物体所属分类
             2.一个标记，定义了哪种物体接触到该物体，该物体会收到通知（谁撞我我会收到通知）
             3.一个标记，定义了哪种物体会碰撞到自己 */
            addChild(node)
            
        }
        
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        currentInex = Int(arc4random()%5 + 1)
       
        label?.texture = SKTexture.init(image: UIImage.init(named: "\(currentInex)")!)
       
    }

    override func didMove(to view: SKView) {
        size = UIScreen.main.bounds.size

        physicsBody = SKPhysicsBody(edgeLoopFrom: frame)

        addStaticShapeNode()
    }

    override func update(_ currentTime: TimeInterval) {
        // Called before each frame is rendered

        // Initialize _lastUpdateTime if it has not already been
        if lastUpdateTime == 0 {
            lastUpdateTime = currentTime
        }

        // Calculate time since last update
        let dt = currentTime - lastUpdateTime

        // Update entities
        for entity in entities {
            entity.update(deltaTime: dt)
        }

        lastUpdateTime = currentTime
    }

    func didBegin(_ contact: SKPhysicsContact) {
        if contact.bodyB.categoryBitMask == contact.bodyA.categoryBitMask {
            contact.bodyB.node?.removeFromParent()

            let nodeb: SKSpriteNode = contact.bodyA.node as! SKSpriteNode
            
            let AB: Int = Int(nodeb.size.width/10)
            nodeb.name = "\(AB+1)"
            nodeb.size = CGSize(width: 10*(AB + 1), height: 10*(AB + 1))
            nodeb.physicsBody = SKPhysicsBody(rectangleOf: nodeb.frame.size)
            nodeb.physicsBody?.categoryBitMask = UInt32((AB+1))
            nodeb.physicsBody?.contactTestBitMask = UInt32((AB+1))
//            nodeb.physicsBody?.collisionBitMask = UInt32((AB+1))
            nodeb.color = badayColor(i: AB)
            nodeb.texture = SKTexture.init(image: UIImage.init(named: "\(AB+1)")!)
            
        }
    }
}

extension GameScene {
    func addStaticShapeNode() {
        let shapeNode = SKShapeNode()
        shapeNode.position = CGPoint.zero
        let path = CGMutablePath()
        let point_1 = CGPoint(x: frame.minX, y: frame.minY + 40)
        let point_2 = CGPoint(x: frame.maxX, y: point_1.y)
        let point_3 = CGPoint(x: point_2.x, y: point_2.y + 10)
        let point_4 = CGPoint(x: point_1.x, y: point_3.y)
        let point_5 = point_1
        path.move(to: point_1)
        path.addLine(to: point_2)
        path.addLine(to: point_3)
        path.addLine(to: point_4)
        path.addLine(to: point_5)
        shapeNode.path = path
//            UIBezierPath.init(rect: CGRect.init(x: 0, y:  (self.view?.bounds.size.height)! - 88, width: (self.view?.bounds.size.width)!, height:10)).cgPath
        shapeNode.strokeColor = UIColor.black // 填充颜色
        shapeNode.fillColor = UIColor.black // 线颜色
//        shapeNode.lineWidth = 1 // 线宽
//        shapeNode.glowWidth = 4 // 光晕
        shapeNode.lineJoin = .round // 线连接方式
        shapeNode.physicsBody = SKPhysicsBody.init(polygonFrom: path) // 设置物理引擎
        shapeNode.physicsBody?.isDynamic = false // 设置为静态物体
        addChild(shapeNode)
    }
    
    func badayColor(i : Int) -> UIColor {
        let colors = [UIColor.red,//            1 0
                      UIColor.orange,//         2 1
                      UIColor.cyan, //          3 2
                      UIColor.yellow,//         4 3
                      UIColor.brown,//          5 4
                      UIColor.green,//          6 5
                      UIColor.purple,//         7 6
                      UIColor.systemPink,//     8 7
                      UIColor.systemTeal,//     9 8
                      UIColor.systemBlue,//    10 9
                      UIColor.systemIndigo] // 11 10
 
        if i > colors.count {
            return UIColor.red
        }
        return colors[i];
        
    }
}

extension UIColor {
    // 返回随机颜色
    class var randomColor: UIColor {
//        let red = CGFloat(arc4random() % 256) / 255.0
//        let green = CGFloat(arc4random() % 256) / 255.0
//        let blue = CGFloat(arc4random() % 256) / 255.0

        let rand = Int(arc4random() % 4)
        let colors = [UIColor.red, UIColor.orange, UIColor.cyan, UIColor.yellow, UIColor.brown]

        return colors[rand]
    }
}
